# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/6/9'
__author__ = 'Just'
__filename__ = 'theme'
"""
from flask import jsonify
from app.libs.error_code import DeleteSuccess, Success, ParameterException, NotFoundException
from app.libs.redprint import Redprint
from app.libs.token_auth import auth
from app.model.base import db
from app.model.comic import Comic
from app.model.theme import Theme
from app.validators.form import ThemeChangeForm, ThemeDataForm
from app.viewmodel.theme import ThemeViewModel, ThemeCollection


api = Redprint('theme')


@api.route('/admin', methods=['GET'])
@auth.login_required
def get_themes():
    """管理员 获取主题列表"""
    theme_list = Theme.get_list_for_admin()
    if not theme_list:
        raise NotFoundException(msg='暂无主题记录数据，请添加', error_code=4010)
    comics = [item.comics.all() for item in theme_list]
    collection = ThemeCollection()
    collection.fill(list(zip(theme_list, comics)))
    return jsonify(collection)


@api.route('', methods=['POST'])
@auth.login_required
def add_theme():
    """添加新主题"""
    form = ThemeChangeForm().validate_for_api()
    Theme.add_theme(form.data)
    return Success(code=201, msg='添加成功')


@api.route('/<int:tid>/update', methods=['POST'])
@auth.login_required
def update_theme(tid):
    """添加新主题"""
    form = ThemeChangeForm().validate_for_api()
    Theme.update_theme(tid, form.data)
    return Success(code=201, msg='更新成功')


@api.route('/<int:tid>', methods=['DELETE'])
@auth.login_required
def remove_theme(tid):
    """移除某主题"""
    theme = Theme.query.get_or_404(tid, msg='主题不存在', error_code=4000)
    with db.auto_commit():
        db.session.delete(theme)
    return DeleteSuccess(msg='已移除')


@api.route('/add', methods=['POST'])
@auth.login_required
def add_theme_data():
    """添加一组 主题子项记录(漫画)"""
    form = ThemeDataForm().validate_for_api()
    tid = form.id.data
    comics_id_new = form.comics.data  # list
    theme = Theme.query.get_or_404(tid, msg='主题不存在', error_code=4000)
    comics = theme.comics.all()
    comics_id = [item.cid for item in comics]
    new_ids = list(set(comics_id_new) - set(comics_id))
    if not new_ids:
        raise ParameterException(msg='这些主题记录数据已存在', error_code=4001)
    with db.auto_commit():
        new_comics = Comic.query.filter(
            Comic.status == 1,
            Comic.cid.in_(new_ids)
        ).all()
        theme.comics.extend(new_comics)
    return Success(code=201, msg='添加成功')


@api.route('/delete', methods=['POST'])
@auth.login_required
def remove_theme_data():
    """移除某主题的子项记录(漫画)"""
    form = ThemeDataForm().validate_for_api()
    tid = form.id.data
    comics_id = form.comics.data  # list
    theme = Theme.query.get_or_404(tid, msg='主题不存在', error_code=4000)
    theme_comics_id = [item.id for item in theme.comics.all()]
    if not theme_comics_id:
        raise NotFoundException(msg='这些主题记录已不存在了', error_code=4001)
    comics_id = list(set(comics_id) & set(theme_comics_id))  # 交集
    if not comics_id:
        raise NotFoundException(msg='这些主题记录已不存在了', error_code=4001)
    with db.auto_commit():
        old_comics = Comic.query.filter(
            Comic.status == 1,
            Comic.cid.in_(comics_id)
        ).all()
        [theme.comics.remove(comic) for comic in old_comics]
    return DeleteSuccess(msg='已移除')
